<?php

class User_Action_Login extends Action
{
	function execute($request)
	{

		$user = Agilet::getViewer();

		if ($user)
		{
			$request -> response = 'you have been logged before!';
			return;
		}

		if (isset($_REQUEST['redirect_uri']))
		{
			$_SESSION['login_redirect_uri'] = urldecode($_REQUEST['redirect_uri']);
		}

		$form = Form::factory('user/login');

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			$email = $data['email'];

			$password = $data['password'];

			$auth = Agilet::getPlugin('user.plugin.auth.database');

			$user = $auth -> authenticate($email, $password);

			if ($user == Auth::INVALID_IDENTITY)
			{
				$form -> addError('email not found');
			}
			else
			if ($user == Auth::INVALID_PASSWORD)
			{
				$form -> addError('password not match');
			}
			else
			if (!$user instanceof User_Model_User)
			{
				// success
				$form -> addError('user and password not match');
			}
			else
			if ($user instanceof User_Model_User)
			{
				$_SESSION['uid'] = $user -> getId();

				if (isset($_SESSION['login_redirect_uri']))
				{
					$url = $_SESSION['login_redirect_uri'];
					unset($_SESSION['login_redirect_uri']);
				}
				else
				{
					$url = Agilet::getUrl('/');
				}
				
				$user->login();
				header('location: ' . $url);
			}

		}

		$request -> response = View::render($script = 'user/html/login', $data = array('form' => $form));
	}

}
